from django.http import JsonResponse
import json
from app01.models import AbsoTotal
from rest_framework.views import APIView
from app01.Baseview import MsgView, BasedAPIView
from django import forms
from django.db.models import Q, Count
from django.db.models import F, ExpressionWrapper, DecimalField, Func
from django.db.models import Sum
from datetime import datetime, timedelta

from app01.woutils.user_jwt import ParseToekn


class AbsoinfoForm(forms.ModelForm):
    class Meta:
        model = AbsoTotal
        fields = ['type_order', 'total_sales', 'total_refund']


class AbsoTotal_Api(BasedAPIView):
    def get_page_all(self, request):
        # uid = request.query_params.get('uid', None)
        uid = request.GET.get('id', None)
        try:
            page = int(request.GET.get["page"])  # 获取get请求传递的参数 page
            pagesize = int(request.GET.get["pagesize"])
        except Exception as e:
            page = 1
            pagesize = 10
        if page < 1:
            page = 1
        type_order = request.GET.getlist("type_order", None)
        CreatedTime = request.GET.getlist("CreatedTime[]", [])
        query = Q()
        if type_order is not None:
            for single_type_order in type_order:
                query |= Q(type_order__iexact=single_type_order)

        if len(CreatedTime) == 1:
            parts = CreatedTime[0].split('-')
            if len(parts) == 3:
                year, month, day = map(int, parts)
                query &= Q(CreatedTime__year=year, CreatedTime__month=month, CreatedTime__day=day)

        data = AbsoTotal.objects.filter(query).values() if query else AbsoTotal.objects.all()
        # 使用 annotate 来添加 Total_transaction 到查询集中
        datas = data.annotate(
            total_transaction=ExpressionWrapper(
                F('total_sales') - F('total_refund'),
                output_field=DecimalField(max_digits=10, decimal_places=2)
            )
        ).values()
            # 'id', 'type_order', 'total_sales', 'Total_refund', 'remarks',
            # 'CreatedTime', 'UpdatedTime', 'Total_transaction'  # 确保包含 Total_transaction

        data_list = []
        for item in datas:
            item['CreatedTime'] = item['CreatedTime'].strftime("%Y-%m-%d")
            data_list.append(item)

        start_page = page * pagesize - pagesize
        end_page = page * pagesize
        paginated_data = data_list[start_page:end_page]
        total = AbsoTotal.objects.filter(query).count()
        total_order_sum = AbsoTotal.objects.filter(query).aggregate(Sum('total_sales'))['total_sales__sum'] or 0
        total_refund_sum = AbsoTotal.objects.filter(query).aggregate(Sum('total_refund'))['total_refund__sum'] or 0
        total_transaction_sum = total_order_sum - total_refund_sum

        data = {
            "total": total,
            "data": paginated_data,
            "total_order_sum": total_order_sum,
            "total_refund_sum": total_refund_sum,
            "total_transaction_sum": total_transaction_sum,
        }
        return super().success(data=data)

    def add_info(self, request):
        form = AbsoinfoForm(json.loads(request.body))
        if form.is_valid():
            form.save()
            return super().success(msg="添加成功", data=form.cleaned_data)
        else:
            return super().error(msg=f"数据添加失败")

    def del_info(self, request):
        uid = request.GET.get('id', "")
        try:
            AbsoTotal.objects.get(pk=uid).delete()
            return super().success(msg="删除成功")
        except AbsoTotal.DoesNotExist:
            return super().error(msg="ID不存在")
    def edit_info(self, request):
        data = json.loads(request.body)
        uid = data.get('id')
        instance = AbsoTotal.objects.get(pk=uid)
        form = AbsoinfoForm(data, instance=instance)
        if form.is_valid():
            form.save()
            return super().success(msg="修改成功", data=form.data)
        else:
            return super().error(msg="数据验证失败")




